import '../../root.css';
import { mainStyle } from './index.css';
import { vars } from '@knno/jsx-ui/theme.css';
import { Button } from '@knno/jsx-ui/components/button';
import { Toast } from '@knno/jsx-ui/components/toast';
import { Dialog } from '@knno/jsx-ui/components/dialog';
import axios from 'axios';
import { render, unsafe } from '@knno/jsx';

let code: HTMLElement;
render(() => {
	return (<main class={mainStyle}>
		<h1>Thor Web Framework Demo</h1>
		<div
			style={{
				marginBottom: '1rem',
				padding: '20px',
				backgroundColor: vars.color.panelBackground,
				borderRadius: '5px',
			}}>
			<code ref={(el) => (code = el)} style={{ fontSize: '24px', whiteSpace: 'pre-line' }}></code>
		</div>
		<Button
			class="button"
			type="primary"
			onclick={async () => {
				try {
					const response = await axios.get<string>('/api/about');
					const tb = response.data;
					const dlg = Dialog.create(unsafe(tb))
						.setAutoClose(true)
						.setButtons(<Button
							onclick={() => {
								dlg.close();
							}}>
							Close
						</Button>)
						.show();
				} catch (e) {
					Toast.show(`Error: ${e}`);
				}
			}}>
			Show Server Environment Variables
		</Button>
		<Button
			type="danger"
			class="button"
			onclick={async () => {
				try {
					await axios.get('/api/auth/logout');
					location.reload();
				} catch (e) {
					Toast.show(`Error: ${e}`);
				}
			}}>
			Logout
		</Button>
	</main>);
});

async function showTime() {
	try {
		const response = await fetch('/api/echo');
		if (response.status == 200) {
			const serverInfo = await response.json();
			code.textContent = `Server Info: ${serverInfo.version}
Total Memory: ${Math.round((serverInfo.totalmem / 1024 / 1024 / 1024) * 100) / 100}G
Free Memory: ${Math.round((serverInfo.freemem / 1024 / 1024 / 1024) * 100) / 100}G`;
		} else {
			code.textContent = response.status + ':' + response.statusText;
		}
	} catch (e) {
		code.textContent = `Error: ${e}`;
	} finally {
		setTimeout(showTime, 5000);
	}
}
showTime();
